/****************************************************************************
  From Qt Examples
****************************************************************************/

#include <QtGui>
#include <QtNetwork>

#include <stdlib.h>

#include "dialog.h"
#include "sslserver.h"

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    statusLabel = new QLabel;
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);


    sslServer = new SSLServer(this);
    if (!sslServer->listen()) {
        QMessageBox::critical(this, tr("Secure Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(sslServer->errorString()));
        close();
        return;
    }

    //Setting up the IP AND THE PORT
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();

    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                            "Run the Secure Client now.")
                         .arg(ipAddress).arg(sslServer->serverPort()));

    //Add the line and text edit
    serverTextEdit = new QTextEdit();
    serverLineEdit = new QLineEdit();

    //SIGNALS/SLOTS
    connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
    connect(serverLineEdit,SIGNAL(returnPressed()),this,SLOT(send()));
    connect((sslServer),SIGNAL(transferMessage(QString)),this,SLOT(readCMsg(QString)));
    //connect(sslServer,SIGNAL(transferMessage(QString)),this,SLOT(send()));

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(quitButton);
    buttonLayout->addStretch(1);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(serverTextEdit);
    mainLayout->addWidget(serverLineEdit);
    mainLayout->addWidget(statusLabel);
    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);

    setWindowTitle(tr("Server"));

}

void Dialog::send()
{
    QString test = serverLineEdit->text();
    test.prepend("Server> ");
    serverTextEdit->append(test);
    sslServer->carryMsgToThread(test);

    serverLineEdit->clear();
}



void Dialog::readCMsg(QString msg)
{
    qDebug() << "MSG Recived!!: " << msg;
    serverTextEdit->append(msg);

}


